package com.fourforfo.fourmall.ware.service.impl;

import com.fourforfo.common.constant.WareConstant;
import com.fourforfo.fourmall.ware.entity.PurchaseDetailEntity;
import com.fourforfo.fourmall.ware.service.PurchaseDetailService;
import com.fourforfo.fourmall.ware.service.WareSkuService;
import com.fourforfo.fourmall.ware.vo.PurchaseDoneItemVO;
import com.fourforfo.fourmall.ware.vo.PurchaseDoneVO;
import com.fourforfo.fourmall.ware.vo.PurchaseMergeVO;
import com.sun.xml.internal.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourforfo.common.utils.PageUtils;
import com.fourforfo.common.utils.Query;

import com.fourforfo.fourmall.ware.dao.PurchaseDao;
import com.fourforfo.fourmall.ware.entity.PurchaseEntity;
import com.fourforfo.fourmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 列出所有未被领取的采购单，即状态为新增和已分配的采购单
     * 用于合并采购需求到整单时的采购单选择
     */
    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                //查询状态为新增和已分配的采购单
                new QueryWrapper<PurchaseEntity>()
                        .eq("status",WareConstant.PurchaseStatusEnum.CREATED.getCode()).or()
                        .eq("status",WareConstant.PurchaseStatusEnum.ASSIGEND.getCode())
        );

        return new PageUtils(page);
    }

    /**
     * /ware/purchase/merge
     * 保存合并采购需求
     */
    @Transactional
    @Override
    public void mergePurchase(PurchaseMergeVO purchaseMergeVO) {

        Long purchaseId = purchaseMergeVO.getPurchaseId();
        //没传入purchaseId则创建一个新的采购单
        if(purchaseId==null||purchaseId==0){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();

        }else{
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }

        List<Long> purchaseDetailIds = purchaseMergeVO.getItems();
        if(purchaseDetailIds!=null&&purchaseDetailIds.size()>0){
            /**
             * 也可以通过 purchaseDetailService.updateBatchById(Conllection);实现
             *  将要修改的数据封装成一个List<PurchaseDetailEntity>集合
             */

            purchaseDetailService.updatePurchaseIdAndStatus(purchaseId,purchaseDetailIds);
        }

    }

    /**
     * /ware/purchase/received
     * 领取采购单
     */
    @Transactional
    @Override
    public void receivedPurchase(List<Long> purchaseIds) {
        List<PurchaseEntity> purchaseEntities = this.listByIds(purchaseIds);
        //1. 确认当前采购单是新建或者已分配状态
        //1.1 过滤出其中是新建或已分配状态的purchaseEntity
        List<PurchaseEntity> purchaseEntityList = purchaseEntities.stream().filter(purchase->
            purchase.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()
            ||purchase.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGEND.getCode()
        ).map(purchase->{
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());//设为已领取的状态
            //TODO 不知道为什么时间不更新
            purchase.setUpdateTime(new Date());
            return purchase;
        }).collect(Collectors.toList());

        //2. 改变采购单的状态
        this.updateBatchById(purchaseEntityList);

        //3. 改变采购需求的状态
        purchaseIds = purchaseEntityList.stream()
                .map(purchase -> purchase.getId())
                .collect(Collectors.toList());
        purchaseDetailService.updateStatusByPurchaseId(purchaseIds);

    }

    /**
     * 完成采购
     * @param purchaseDoneVO
     */
    @Transactional
    @Override
    public void donePurchase(PurchaseDoneVO purchaseDoneVO) {
        //TODO 可以对purchase的状态进行一下限制，如果数据库中的purchaseDetail的status不是已领取和失败的状态，则返回异常
        //1. 改变采购项的状态,即更新PurchaseDetail
        Boolean flag = true;
        List<PurchaseDetailEntity> updateItems = new ArrayList<>();//用于更新的PurchaseDetailEntity集合
        /**
         * 保存采购成功的订单项id
         * 用于第三步将成功采购的订单项入库
         */
        List<Long> finishPurchaseIds = new ArrayList<>();
        for(PurchaseDoneItemVO item:purchaseDoneVO.getItems()){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());

            }else{
                //成功的收集起来用于入库操作
                purchaseDetailEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
                finishPurchaseIds.add(item.getItemId());
            }
            purchaseDetailEntity.setId(item.getItemId());

            updateItems.add(purchaseDetailEntity);
            
        }

        purchaseDetailService.updateBatchById(updateItems);

        //2. 改变采购单状态
        /*
        TODO 此id不应该从前端传入，可以通过itemId来获取其purchaseId，
         又或者只传入purchaseId，查看purchase的状态，
         如果状态为已领取且其所有的purchaseDetail的状态都是已领取,则进行更新
         */
        Long id = purchaseDoneVO.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        //2.1 判断是否所有采购项都成功，都成功则设该采购单状态完成，否则状态设为HASERROR
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        //3. 将成功采购的进行入库
        //3.1 查出所有成功的订单项的详细数据
        //3.2 批量保存成功的订单项信息
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(finishPurchaseIds);
        wareSkuService.saveFinishPurchaseDetail(purchaseDetailEntities);
    }

}